﻿using System;
using System.Collections.Generic;
using System.Text;
using EnvDTE;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.Diagnostics;
using Microsoft.VisualStudio.CommandBars;

namespace TFSPlus
{
    public static class TFSPlusCommon
    {

        public static string GetCurrentNavigate()
        {
            if (Connect.VersionControlExt.Explorer.CurrentFolderItem == null)
                return "";

            return Connect.VersionControlExt.Explorer.CurrentFolderItem.SourceServerPath;
        }

        public static void NavigateTo(string serverPath)
        {
            if (!String.IsNullOrEmpty(serverPath))
            {
                Connect.VersionControlExt.Explorer.Navigate(serverPath);
                foreach (Window w in Connect.ApplicationObject.Windows)
                {
                    if (w.Caption == "Source Control Explorer")
                    {
                        w.SetFocus();
                        break;
                    }
                }
                return;
            }
        }


        /// <summary>
        /// Gets the name of the file path.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        public static string GetFilePath(object o)
        {
            if (o is EnvDTE.Solution)
            {
                EnvDTE.Solution solution = (EnvDTE.Solution)o;
                return solution.FullName;
            }
            else if (o is EnvDTE.Project)
            {
                EnvDTE.Project project = (EnvDTE.Project)o;
                //if (IsWebProject(project))
                //{
                //    return project.Properties.Item("FullPath").Value.ToString() + "\\";
                //}
                //else
                {
                    return project.FullName;
                }
            }
            else if (o is EnvDTE.ProjectItem)
            {
                EnvDTE.ProjectItem projectItem = (EnvDTE.ProjectItem)o;

                // A 'ProjectItem' can be a sub project, a folder (or a file)
                if (projectItem.SubProject != null)
                {
                    return GetFilePath(projectItem.SubProject);
                }
                else
                {
                    // we return the full path of the folder (or the file)
                    //    _logger.DebugFormat("The selected item is a '{0}' folder or a file : ", projectItem.get_FileNames(0));
                    return projectItem.get_FileNames(0);
                }
            }
            else
            {
                //throw new System.NullReferenceException("Full path not found for the selected item");
                return "";
            }
        }


        private static OutputWindowPane generalOutputPane = null;
        public static void OutputGeneralString(string message)
        {
            if (generalOutputPane == null)
            {
                foreach (OutputWindowPane outWindowPane in Connect.ApplicationObject.ToolWindows.OutputWindow.OutputWindowPanes)
                {
                    if (outWindowPane.Name == "TFSPlus")
                    {
                        generalOutputPane = outWindowPane;
                    }
                }
                if (generalOutputPane == null && Connect.ApplicationObject.ToolWindows.OutputWindow.OutputWindowPanes.Count > 0)
                {
                    generalOutputPane = Connect.ApplicationObject.ToolWindows.OutputWindow.OutputWindowPanes.Add("TFSPlus");
                }
                if (generalOutputPane != null)
                {
                    generalOutputPane.Activate();
                }
            }

            if (generalOutputPane != null)
            {
                generalOutputPane.OutputString(message + "\r\n");
            }
        }

        public static void OutputCommandBars()
        {
            OutputGeneralString("CommandBars");
            OutputGeneralString("-----------");
            foreach (CommandBar cb in (CommandBars)Connect.ApplicationObject.CommandBars)
            {
                OutputGeneralString("   " + cb.Name + "\r\n");
            }
        }


        public static bool IsCheckedOutByMe(Workspace workspace, string filePath)
        {
            PendingSet[] pendingSets = workspace.QueryPendingSets(new string[] { filePath }, RecursionType.None, null, GetUsername(workspace.VersionControlServer.TeamFoundationServer), false);

            // should only be one pending set!
            Debug.Assert(pendingSets.Length < 2);

            foreach (PendingSet ps in pendingSets)
            {
                return ps.PendingChanges[0].IsEdit;
            }
            return false;
        }


        public static void GetServerPathLocalPath(Workspace workspace, string filePath, out string serverPath, out string localPath)
        {
            if (filePath.StartsWith("$/"))
            {
                serverPath = filePath;
                localPath = workspace.TryGetLocalItemForServerItem(serverPath);
            }
            else
            {
                serverPath = workspace.TryGetServerItemForLocalItem(filePath);
                localPath = workspace.TryGetLocalItemForServerItem(serverPath);
            }
        }

        public static String GetUsername(Microsoft.TeamFoundation.Client.TeamFoundationServer tfsServer)
        {
            // This method requires two references that are probably otherwise not needed
            //      Microsoft.TeamFoundation 
            //      Microsoft.TeamFoundation.Common

            if (tfsServer == null || tfsServer.AuthenticatedUserIdentity == null)
                return "";
            else
                return tfsServer.AuthenticatedUserIdentity.AccountName;
        }

    }
}
